package com.lagou.mall.esflow.server.config;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.DefaultKafkaProducerFactory;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class KafkarConfig {


    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;


    @PostConstruct
    public void init() {
        DefaultKafkaProducerFactory producerFactory = (DefaultKafkaProducerFactory) kafkaTemplate.getProducerFactory();
        Map<String, Object> configurationMap = new HashMap<>();
        configurationMap.put(ProducerConfig.PARTITIONER_CLASS_CONFIG, "com.lagou.study.kafka.CustomerPartitioner");
        producerFactory.updateConfigs(configurationMap);

    }

    @PreDestroy
    public void destroy() {
        if (null != kafkaTemplate) {
            kafkaTemplate.destroy();
        }
    }


    public KafkaConsumer<String,String> createConsumer(
            KafkaTemplate kafkaTemplate,
            String topic
    ) {
        final KafkaConsumer<String, String> consumer = new KafkaConsumer<String, String>(
                kafkaTemplate.getProducerFactory().getConfigurationProperties());
        consumer.subscribe(Collections.singleton(topic));
        return consumer;
    }
}